package org.lightmtv.filters;

import java.util.Locale;

import javax.servlet.http.Cookie;

import org.lightcommons.util.ConvertUtils;
import org.lightcommons.util.StringUtils;
import org.lightcommons.web.auth.AuthManager;
import org.lightcommons.web.auth.IUser;
import org.lightmtv.config.GlobalContext;
import org.lightmtv.config.MtvFilterChain;
import org.lightmtv.request.Request;
import org.lightmtv.response.Response;

public class I18nFilter extends AbstractMtvFilter {

	private static String AVARIBLE_LOCALES_NAME="avariable.locales";
	private static String I18N_COOKIE_NAME="lightmtv.lang";
	private Locale[] avariableLocales;
	public I18nFilter() {
		String al= GlobalContext.getSettings().getProperty(AVARIBLE_LOCALES_NAME);
		if(!StringUtils.hasText(al)){
			avariableLocales = new Locale[]{Locale.getDefault()};
		}else{
			String[] als = al.split(",");
			for(int i=0;i<als.length;i++){
				avariableLocales[i]=ConvertUtils.localeOf(als[i]);
			}
		}
	}
	
	public Response doFilter(Request request, MtvFilterChain chain) {
		//1. 由参数决定Locale
		String lang = request.getParam("lang");
		if(StringUtils.hasText(lang)){
			Locale locale = ConvertUtils.localeOf(lang);
			GlobalContext.setLocale(locale);
			Response response = chain.doFilter(request);
			Cookie cookie = new Cookie(I18N_COOKIE_NAME,lang);
			cookie.setMaxAge(-1);
			response.addCookie(cookie);
			return response;
		}
		//2. 由Cookie决定Locale
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie cookie: cookies){
				if(I18N_COOKIE_NAME.equals(cookie.getName())){
					Locale locale = ConvertUtils.localeOf(cookie.getValue());
					GlobalContext.setLocale(locale);
					return chain.doFilter(request);
				}
			}
		}
		//3. 由用户证书决定Locale
		IUser user = AuthManager.getUser();
		if(user!=null && user.getLocale()!=null){
			GlobalContext.setLocale(user.getLocale());
			return chain.doFilter(request);
		}
		//4. 由http头信息决定Locale
		Locale locale = request.getBestLocaleIn(avariableLocales);
		GlobalContext.setLocale(locale);
		return chain.doFilter(request);
	}
	
}
